import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { authService, userService, LoginCredentials, UserInfo } from '@repo/api';

interface UserState {
  // 用户认证状态
  isLoggedIn: boolean;
  userInfo: UserInfo | null;
  accessToken: string | null;
  refreshToken: string | null;
  loading: boolean;
  error: string | null;
  
  // 用户认证操作
  login: (credentials: LoginCredentials) => Promise<boolean>;
  logout: () => Promise<void>;
  clearError: () => void;
  initializeAuth: () => Promise<void>;
  fetchUserProfile: () => Promise<boolean>;
}

const useUserStore = create<UserState>()(
  persist(
    (set) => ({
      // 初始状态
      isLoggedIn: false,
      userInfo: null,
      accessToken: null,
      refreshToken: null,
      loading: false,
      error: null,

      // 用户登录
      login: async (credentials: LoginCredentials) => {
        set({ loading: true, error: null });
        
        try {
          const response = await authService.login(credentials);
          
          if (response.data.success && response.data.data) {
            const { access_token, refresh_token, subject_info } = response.data.data;
            
            set({
              isLoggedIn: true,
              userInfo: subject_info as UserInfo,
              accessToken: access_token,
              refreshToken: refresh_token,
              loading: false,
              error: null
            });
            
            return true;
          } else {
            set({
              loading: false,
              error: '登录失败'
            });
            return false;
          }
        } catch (error: any) {
          const errorMessage = error?.response?.data?.error || error?.message || '登录失败，请稍后重试';
          
          set({
            loading: false,
            error: errorMessage
          });
          
          return false;
        }
      },

      // 用户退出登录
      logout: async () => {
        // 退出登录时不需要设置 loading 状态，直接清空状态
        try {
          await authService.logout();
        } catch (error) {
          console.error('退出登录请求失败:', error);
        } finally {
          // 清空所有状态，persist 会自动清除 localStorage
          set({
            isLoggedIn: false,
            userInfo: null,
            accessToken: null,
            refreshToken: null,
            loading: false,
            error: null
          });
        }
      },

      // 清除错误信息
      clearError: () => {
        set({ error: null });
      },

      // 获取用户信息
      fetchUserProfile: async () => {
        set({ loading: true, error: null });
        
        try {
          const response = await userService.getCurrentUser();
          
          if (response.data.success && response.data.data) {
            const userData = response.data.data;
            // 转换数据格式以匹配 UserInfo 接口
            const userInfo: UserInfo = {
              ...userData,
              email_verified_at: userData.email_verified_at || null,
              phone: userData.phone || null,
              phone_verified_at: userData.phone_verified_at || null,
              nickname: userData.nickname || null,
              avatar: userData.avatar || null,
              last_login_ip: userData.last_login_ip || null,
              locked_until: userData.locked_until || null,
              settings: userData.settings || null,
              last_login_at: userData.last_login_at || null
            };
            
            set({
              userInfo,
              isLoggedIn: true,
              loading: false,
              error: null
            });
            return true;
          } else {
            set({
              loading: false,
              error: '获取用户信息失败'
            });
            return false;
          }
        } catch (error: any) {
          // 401错误表示未认证，不设置错误信息，静默失败
          if (error?.response?.status === 401) {
            set({
              loading: false,
              isLoggedIn: false,
              userInfo: null,
              accessToken: null,
              refreshToken: null,
              error: null
            });
            return false;
          }
          
          // 其他错误才设置错误信息
          const errorMessage = error?.response?.data?.error || error?.message || '获取用户信息失败';
          
          set({
            loading: false,
            error: errorMessage,
            isLoggedIn: false,
            userInfo: null,
            accessToken: null,
            refreshToken: null
          });
          
          return false;
        }
      },

      // 初始化用户认证状态
      initializeAuth: async () => {
        const state = useUserStore.getState();
        
        // 如果没有token，直接清除状态
        if (!state.accessToken) {
          set({
            isLoggedIn: false,
            userInfo: null,
            accessToken: null,
            refreshToken: null,
            loading: false,
            error: null
          });
          return;
        }
        
        // 有token时，尝试获取用户信息来验证登录状态
        console.info('验证登录状态，获取用户信息...');
        const success = await state.fetchUserProfile();
        
        if (!success) {
          // 获取用户信息失败（可能是401未认证），清除认证状态
          console.info('登录状态验证失败，清除认证信息');
          set({
            isLoggedIn: false,
            userInfo: null,
            accessToken: null,
            refreshToken: null,
            loading: false,
            error: null
          });
        } else {
          console.info('登录状态验证成功');
        }
      }
    }),
    {
      name: 'user-store',
      partialize: (state) => ({
        isLoggedIn: state.isLoggedIn,
        userInfo: state.userInfo,
        accessToken: state.accessToken,
        refreshToken: state.refreshToken
      })
    }
  )
);

export default useUserStore;
